<template>
  <div class="addBpm">
    <Form :model="bpmModel" ref="approvalForm" :rules="ruleValidate" :label-width="100">
      <Col span="20">
        <Form-item label="流程名称" prop="name" :label-width="150">
          <Input type="text" v-model="bpmModel.name" placeholder="请输入流程名称" :disabled="readOnly"></Input>
        </Form-item>
      </Col>

      <Row :gutter="10" v-if="!readOnly">
        <Col span="20">
          <Form-item label="选择模板" prop="templateType" :label-width="150">
            <Select size="default" v-model="bpmModel.templateType">
              <Option v-for="item in moduleOptions" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
      <Col span="20" v-if="bpmModel.templateType === 4">
        <Form-item label="流程ID" prop="bpmId" :label-width="150">
          <div style="display: flex;">
            <Input type="text" v-model="bpmModel.bpmId" placeholder="请输入流程ID"></Input>
            <Button type="text" @click="goBpmp" html-type="button">设置审批流</Button>
          </div>
        </Form-item>
      </Col>
      <Col span="20">
        <Form-item label="配置审批用户" :label-width="150" label-position="top">
          <Table :columns="approveColumns" :data="approveData" border></Table>
          <div style="text-align: end;" v-if="!readOnly">
            <RPButton
              type="button"
              optType="create"
              text="新增"
              html-type="button"
              style="width:100%"
              icon="md-add"
              @click="addRow"
            />
          </div>
        </Form-item>
      </Col>

      <Row :gutter="10">
        <Col span="20">
          <Form-item label="备注" prop="remark" :label-width="150">
            <Input
              type="textarea"
              :rows="4"
              v-model="bpmModel.remark"
              placeholder="请输入备注"
              :disabled="readOnly"
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="10" v-if="showForms">
        <Col span="20">
          <Form-item label="已关联表单" prop="formList" :label-width="150">
            <Tag
              type="border"
              v-for="item in bpmModel.formList"
              :key="item.id"
              :name="item"
              :closable="tagcClosable(item)"
              @on-close="handleClose"
              >{{ item.name }}</Tag
            >
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import steps from './components/steps.vue'
import SelectUserPage from './components/SelectUser.vue'
import SelectOrgPage from './components/SelectOrg.vue'
import bpmpCenterApi from '@/api/bpmCenter.js'
import { mapState } from 'vuex'
import {
  STATUS_TYPE_DRAFT,
  STATUS_TYPE_PENDING,
  STATUS_TYPE_REVIEW,
  STATUS_TYPE_APPROVED,
  STATUS_TYPE_REJECTED,
  STATUS_TYPE_FINISH
} from '@/views/formConst'
export default {
  components: {},
  data() {
    return {
      showForms: false,
      bpmModel: {
        templateType: 0,
        year: new Date().getFullYear(),
        formType: 2,
        name: '',
        bpmId: '',
        remark: '',
        formIdList: [],
        formList: [],
        config: ''
      },
      ruleValidate: {
        name: [{ required: true, message: '请填写流程名称', trigger: 'blur' }],
        bpmMould: [{ required: true, type: 'number', message: '请选择模板', trigger: 'change' }],
        bpmId: [{ required: true, message: '请填写流程ID', trigger: 'blur' }]
        // formList: [{ required: true, type: 'array', message: '请选择关联表单', trigger: 'blur' }]
      },
      moduleOptions: [
        { label: '自动审批', value: 0 },
        { label: '一轮业务审批', value: 1 },
        { label: '二轮业务审批', value: 2 },
        { label: '三轮业务审批', value: 3 },
        { label: '自主配置流程', value: 4 }
      ],
      config: {
        isOrg: true,
        configGroups: [
          {
            org: [],
            submitter: {},
            approver: {},
            vars: {
              approver1: '',
              approver2: '',
              approver3: ''
            }
          }
        ]
      },
      approveData: [
        {
          fill: [],
          approver1: [],
          approver2: [],
          approver3: []
        }
      ],
      flatOrg: [],
      orgDatas: [],
      loading: false,
      associate: [
        {
          text: '关联表单',
          theme: 'primary',
          handle: () => {
            // this.handleConnect()
            //   .bpmpAssociate({
            //     bpmpId: this.id,
            //     formId: this.formId
            //   })
            //   .then(res => {
            //     if (res.data.code == 200) {
            //       this.$Message.success({
            //         content: '关联成功',
            //         duration: 3
            //       })
            //       this.$emit('Close', true)
            //     } else {
            //       this.$Message.error({
            //         content: res.data.msg || '关联失败',
            //         duration: 3
            //       })
            //     }
            //   })
          }
        }
      ],
      actions: [
        {
          text: '模板预览',
          theme: 'primary',
          handle: () => {
            this.previewFormModal()
          }
        },
        {
          text: '提交',
          theme: 'primary',
          handle: () => {
            if (this.isEmptyApproveData()) {
              return
            }
            this.$refs['approvalForm']
              .validate(valid => {
                if (valid) {
                  this.approveData2Config()
                  const config = JSON.stringify(this.config)
                  this.loading = true
                  bpmpCenterApi.bpmpSubmit({ ...this.bpmModel, config }).then(res => {
                    this.loading = false
                    if (res.data.code == 200) {
                      this.$Message.success({
                        content: '新增成功',
                        duration: 3
                      })
                      this.id = res.data.data
                      this.initDataById()
                    }
                  })
                }
              })
              .catch(e => {
                this.loading = false
              })
          },
          loading: this.loading
        },
        {
          text: '暂存',
          theme: 'primary',
          handle: () => {
            this.approveData2Config()
            const config = JSON.stringify(this.config)
            this.loading = true
            bpmpCenterApi
              .bpmpSaveOrUpdate({ ...this.bpmModel, config })
              .then(res => {
                this.loading = false
                if (res.data.code == 200) {
                  this.$Message.success({
                    content: '暂存成功',
                    duration: 3
                  })
                  this.id = res.data.data
                  this.initDataById()
                }
              })
              .catch(e => {
                this.loading = false
              })
          },
          loading: this.loading
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ],
      readActions: [
        {
          text: '模板预览',
          theme: 'primary',
          handle: () => {
            this.previewFormModal()
          }
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ],
      readOnly: true
    }
  },
  computed: {
    ...mapState(['orgList']),
    approveColumns() {
      const list = [
        {
          title: '填报',
          render: this.approveRender('fill', true),
          renderHeader: (h, params) => {
            return [
              h('div', [
                !this.config.isOrg ? '当前模式为:选择用户填报' : '当前模式为:选择组织填报',
                h(
                  'Tooltip',
                  {
                    props: {
                      transfer: true,
                      'max-width': '500',
                      placement: 'right',
                      content: '默认为组织填报，若需选择用户填报，请点击按钮切换'
                    }
                  },
                  [
                    h('Icon', {
                      props: {
                        type: 'ios-help-circle-outline'
                      }
                    })
                  ]
                )
              ]),
              h('i-switch', {
                props: {
                  size: 'large',
                  disabled: this.readOnly,
                  value: this.config.isOrg,
                  beforeChange: () => {
                    let val = this.config.isOrg ? '选择用户填报' : '选择组织填报'
                    return new Promise(resolve => {
                      this.$confirm({
                        type: 'success',
                        title: `切换为填报模式`,
                        content: `是否切换为${val}?`
                      })
                        .then(() => {
                          resolve()
                          this.approveData.forEach(element => {
                            element.fill = []
                          })
                        })
                        .catch(() => {})
                    })
                  }
                },
                // style: {
                //   width: '200px'
                // },
                on: {
                  'on-change': value => {
                    this.config.isOrg = value
                  }
                },
                scopedSlots: {
                  open: () => h('span', '组织'),
                  close: () => h('span', '用户')
                }
              })
            ]
          }
        },
        {
          title: '审批一',
          render: this.approveRender('approver1', false)
        },
        {
          title: '审批二',
          render: this.approveRender('approver2', false)
        },
        {
          title: '审批三',
          render: this.approveRender('approver3', false)
        },
        {
          title: '操作',
          align: 'left',
          fixed: 'right',
          width: 160,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    type: 'text',
                    text: '删除',
                    hidden: this.readOnly,
                    handle: () => {
                      this.deleteRow(params.index)
                    }
                  }
                ]
              }
            })
          }
        }
      ]

      if (this.bpmModel.templateType < 3) {
        list.splice(this.bpmModel.templateType + 1, 3 - this.bpmModel.templateType)
      }
      if (this.readOnly) {
        list.pop()
      }
      return list
    }
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    formId: {
      type: String,
      default: ''
    }
  },
  watch: {
    orgList(newValue, oldValue) {
      this.orgDatas = newValue
    },
    orgDatas(newValue, oldValue) {
      this.flatOrg = this.treeToFlat(newValue)
    }
  },
  created() {},
  mounted() {
    if (this.orgList.length <= 0) {
      this.$store.dispatch('getOrgList')
    } else {
      this.orgDatas = this.orgList
    }
    if (this.id) {
      this.initDataById()
    } else {
      this.readOnly = false
      this.$emit('SetTitle', '新建流程')
      this.$emit('SetPageActions', this.actions)
    }
  },
  methods: {
    initDataById() {
      bpmpCenterApi.bpmpGetById({ id: this.id }).then(res => {
        this.bpmModel = res.data
        if (this.bpmModel.status == STATUS_TYPE_FINISH) {
          this.readOnly = true
          this.showForms = true
          this.$emit('SetTitle', '查看流程')
          this.$emit('SetPageActions', this.readActions)
          //关联表单移到列表页
        } else {
          this.readOnly = false
          this.$emit('SetTitle', '编辑流程')
          this.$emit('SetPageActions', this.actions)
        }
        this.bpmModel.formIdList = this.bpmModel.formList.map(item => item.id)
        this.config = JSON.parse(res.data.config)
        this.config2ApproveData()
      })
    },
    treeToFlat(tree, parentId = null) {
      let flat = []
      for (let node of tree) {
        let copy = { ...node, parentId }
        flat.push(copy)
        if (node.children && node.children.length > 0) {
          flat = flat.concat(this.treeToFlat(node.children, node.id))
        }
      }
      return flat
    },
    uniqueByKey(arr, key) {
      const seen = new Set()
      return arr.filter(item => {
        const serializedKey = JSON.stringify(item[key])
        return seen.has(serializedKey) ? false : seen.add(serializedKey)
      })
    },
    tagcClosable(item) {
      if (![STATUS_TYPE_APPROVED, STATUS_TYPE_FINISH].includes(Number(item.status))) {
        return false
      } else {
        if (this.formId) {
          if (item.id == this.formId) {
            return true
          } else {
            return false
          }
        } else {
          return true
        }
      }
    },
    handleClose(event, form) {
      this.$confirm({
        title: '解绑表单',
        content: '您是否要继续解绑表单?'
      }).then(res => {
        bpmpCenterApi
          .bpmpAssociate({
            bpmpId: this.id,
            formId: form.id
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$Message.success({
                content: '解绑成功',
                duration: 3
              })
              this.initDataById()
            } else {
              this.$Message.error({
                content: res.data.msg || '关联失败',
                duration: 3
              })
            }
          })
      })

      // let index = this.bpmModel.formList.indexOf(form)
      // let idIndex = this.bpmModel.formIdList.indexOf(form.id)
      // if (index > -1) {
      //   this.bpmModel.formList.splice(index, 1)
      // }
      // if (idIndex > -1) {
      //   this.bpmModel.formIdList.splice(idIndex, 1)
      // }
    },
    isEmptyApproveData() {
      let fillEmpty = 0
      let approveEmpty = 0
      this.approveData.forEach(item => {
        if (item.fill.length == 0) {
          fillEmpty = fillEmpty + 1
        }
        if (this.bpmModel.templateType == 1) {
          if (item.approver1.length == 0) {
            approveEmpty = approveEmpty + 1
          }
        } else if (this.bpmModel.templateType == 2) {
          if (item.approver1.length == 0 || item.approver2.length == 0) {
            approveEmpty = approveEmpty + 1
          }
        } else if (this.bpmModel.templateType == 3) {
          if (item.approver1.length == 0 || item.approver2.length == 0 || item.approver3.length == 0) {
            approveEmpty = approveEmpty + 1
          }
        }
      })
      if (fillEmpty > 0) {
        this.$Message.error({
          content: '请添加填报人',
          duration: 3
        })
        return true
      } else if (approveEmpty > 0) {
        this.$Message.error({
          content: '请添加审批人',
          duration: 3
        })
        return true
      }
      return false
    },

    cancel() {
      this.$emit('Close')
    },
    approveData2Config() {
      this.config.configGroups = []
      this.approveData.forEach(item => {
        let configGroup = { org: [], submitter: {}, approver: {}, vars: {} }
        if (this.config.isOrg) {
          item.fill.forEach(org => {
            configGroup.org.push(this.dealOrgPath(org.orgPath))
          })
        } else {
          item.fill.forEach(user => {
            configGroup.submitter[user.userId] = user
          })
        }
        Object.keys(item).forEach(key => {
          if (key.startsWith('approver')) {
            const approvers = []
            item[key].forEach(user => {
              approvers.push(user.userId)
              configGroup.approver[user.userId] = user
            })
            configGroup.vars[key] = approvers.join(' ')
          }
        })
        this.config.configGroups.push(configGroup)
      })
    },
    config2ApproveData() {
      this.approveData = []
      this.config.configGroups.forEach(item => {
        let approve = { fill: [], approver1: [], approver2: [], approver3: [] }
        if (this.config.isOrg) {
          item.org.forEach(data => {
            approve.fill.push({ orgPath: data })
          })
        } else {
          Object.keys(item.submitter).forEach(key => {
            approve.fill.push(item.submitter[key])
          })
        }
        Object.keys(item.vars).forEach(key => {
          item.vars[key].split(' ').forEach(userId => {
            if (userId) {
              approve[key].push(item.approver[userId])
            }
          })
        })
        this.approveData.push(approve)
      })
    },
    approveRender(key, refSelectUser, limit) {
      return (h, params) => {
        let arr = params.row[key] || []
        let renderArray = [
          arr.map((item, index) => {
            return h(
              'Tag',
              {
                props: {
                  type: 'border',
                  closable: !this.readOnly
                },
                on: {
                  'on-close': () => {
                    this.approveData[params.index][key].splice(index, 1)
                  }
                }
              },
              refSelectUser && this.config.isOrg
                ? this.flatOrg.find(
                    org => org.orgPath == item['orgPath'] || this.dealOrgPath(org.orgPath) == item['orgPath']
                  )['orgName']
                : item['userName']
            )
          })
        ]
        if (!this.readOnly && (!limit || arr.length < limit)) {
          renderArray.push(
            h('RPButton', {
              attrs: {
                icon: 'md-add',
                size: 'small',
                text: '添加'
              },
              props: {
                optType: 'create'
              },
              on: {
                click: () => {
                  if (refSelectUser && this.config.isOrg) {
                    new this.$pageModal(
                      SelectOrgPage,
                      {
                        props: { orgDatas: this.orgDatas }
                      },
                      data => {
                        if (data) {
                          this.approveData[params.index][key].push(...data)
                          this.approveData[params.index][key] = this.uniqueByKey(
                            this.approveData[params.index][key],
                            'orgId'
                          )
                        }
                      }
                    )
                  } else {
                    new this.$pageModal(
                      SelectUserPage,
                      {
                        props: { orgDatas: this.orgDatas }
                      },
                      data => {
                        if (data) {
                          const approver = this.approveData[params.index]
                          let hasRepeat = false
                          Object.keys(approver).forEach(key => {
                            if (key.startsWith('approver') && !hasRepeat) {
                              data.forEach(user => {
                                let repeat = approver[key].find(item => item.userId == user.userId)
                                if (repeat) {
                                  hasRepeat = true
                                }
                              })
                            }
                          })
                          if (hasRepeat) {
                            this.$Message.error({
                              content: `人员重复，添加失败`,
                              duration: 3
                            })
                          } else {
                            this.approveData[params.index][key].push(...data)
                          }
                        }
                      }
                    )
                  }
                }
              }
            })
          )
        }
        return h('div', renderArray)
      }
    },
    addRow() {
      const [last] = this.approveData.slice(-1)
      this.approveData.push(JSON.parse(JSON.stringify(last)))
    },
    deleteRow(index) {
      if (this.approveData.length == 1) {
        this.$Message.error({
          content: '请至少保留一行',
          duration: 3
        })
      } else {
        this.approveData.splice(index, 1)
      }
    },
    dealOrgPath(orgPath) {
      return orgPath.substring(orgPath.indexOf('/'))
    },
    previewFormModal() {
      new this.$pageModal(
        steps,
        {
          props: {}
        },
        data => {
          // data && this.searchValueSet()
        }
      )
    },
    goBpmp() {
      window.open('https://bpmp.crc.com.cn/portal/console', '_blank')
    }
  }
}
</script>

<style lang="less" scoped>
.addBpm {
  margin-top: 20px;
}
</style>
